package com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.util

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAttribution
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.AdjustEvent
import com.adjust.sdk.LogLevel
import com.google.gson.Gson
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.AESCryptUtil
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.apiHostCommonCombine
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.event.IAnalyticsEvent
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.http.HttpHelper

object AdjustUtil {

    /** adjust env */
    const val AJ_ENVIRONMENT = AdjustConfig.ENVIRONMENT_PRODUCTION // 填写对应的环境
    //if (BuildConfig.DEBUG) AdjustConfig.ENVIRONMENT_SANDBOX else AdjustConfig.ENVIRONMENT_PRODUCTION

    /** adjust token */
    const val AJ_TOKEN = "bafd34stxgqo" // 填写对应的值

    /** adjust 注册事件码 */
    const val AJ_EVENT_REGISTER = "d6ktwm" // 填写对应的值

    /** adjust 申请事件码 */
    const val AJ_EVENT_APPLY = "9k0fem" // 填写对应的值

    /** 归因信息 */
//    var adjsutAttribution: ParamAdjustInstall? = null
    var adjsutAttribution: HashMap<String, Any> = HashMap<String, Any>().createApiAction()

    /**
     * 初始化Adjust模块
     * 按配置需要来初始化
     *
     * @param context Application
     */
    fun init(context: Application) {
        // 按需要判断，目标是 3个key值不能为空
        if (AJ_TOKEN.isBlank()) throw Exception("Error: Adjust Token must no be null!")
        if (AJ_EVENT_REGISTER.isBlank()) throw Exception("Error: Adjust Register code must no be null!")
        if (AJ_EVENT_APPLY.isBlank()) throw Exception("Error: Adjust Apply code must no be null!")

        val config = AdjustConfig(context, AJ_TOKEN, AJ_ENVIRONMENT)

        // 日志级别
        config.setLogLevel(LogLevel.INFO)

        // 监听归因回调
        config.setOnAttributionChangedListener { covertAndSaveAttributtion(it) }

        // 初始化
        Adjust.onCreate(config)

        // 配置页面监听
        registerAdjustActivityLifecycle(context)

        // 获取当前归因信息
        // 每次初始化都需要重新获取，
        // 因为 setOnAttributionChangedListener 不一定回调多次
        val attribution = Adjust.getAttribution()
        covertAndSaveAttributtion(attribution)
    }

    /**
     * 过滤Adjsut归因信息，
     * 并上传
     *
     * @param attribution AdjustAttribution
     */
    private fun covertAndSaveAttributtion(attribution: AdjustAttribution?) {
        attribution?.let { result ->
            adjsutAttribution.apply { ->
                put("adid", result.adid.orEmpty())
                put("network", result.network.orEmpty())
                put("adgroup", result.adgroup.orEmpty())
                put("creative", result.creative.orEmpty())
                put("costType", result.costType.orEmpty())
                put("campaign", result.campaign.orEmpty())
                put("clickLabel", result.clickLabel.orEmpty())
                put("trackerName", result.trackerName.orEmpty())
                put("trackerToken", result.trackerToken.orEmpty())
                put("costCurrency", result.costCurrency.orEmpty())
                put("fbInstallReferrer", result.fbInstallReferrer.orEmpty())
                put("deviceId", AnalyticsUtil.getAdId())

                result.costAmount?.let { costAmount ->
                    put("costAmount", costAmount.toString())
                }

                //上报
                println("=====adjust attribution:")
                println(this)
                saveInstallInfo()
            }
        }
    }

    /**
     * 配置Adjust 页面监听
     * 如果其它模块有注册callback
     * 注意调用顺序或合并adjus
     *
     * @param context Application
     */
    fun registerAdjustActivityLifecycle(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityResumed(p0: Activity) {
                Adjust.onResume()
            }

            override fun onActivityPaused(p0: Activity) {
                Adjust.onPause()
            }

            override fun onActivityStopped(p0: Activity) {
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }

    /**
     * 打点
     *
     * @param event 事件名
     */
    fun addEvent(event: IAnalyticsEvent) {
        try {
            when (event) {
                IAnalyticsEvent.AT_REGISTER -> {
                    Adjust.trackEvent(AdjustEvent(AJ_EVENT_REGISTER))
                }

                IAnalyticsEvent.AT_LOAN_APPLY -> {
                    Adjust.trackEvent(AdjustEvent(AJ_EVENT_APPLY))
                }

                else -> {}
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 保存Appsflyer 安装信息
     */
    fun saveInstallInfo() {
        try {
            adjsutAttribution.apply {
                put("path", "GiJ5vnTVEB1YWFyMTBVSsA")
            }
            val content = Gson().toJson(adjsutAttribution).trim()
            println("aes before：\n $content")

            // 加密后
            val body: String = AESCryptUtil.encryptDefault(content)
            println("aes after：\n $body")

            HttpHelper.postData(apiHostCommonCombine(), body)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}